/**
 * 描述: 业务逻辑处理 - 用户相关接口
 * 作者: Jack Chen
 * 日期: 2020-06-20
 */


const userService = require('../db/controller/userService')
const md5 = require('../utils/md5');
const jwt = require('jsonwebtoken');
const boom = require('boom');
const { body, validationResult } = require('express-validator');
const {
    CODE_ERROR,
    CODE_SUCCESS,
    PRIVATE_KEY,
    JWT_EXPIRED
} = require('../utils/constant');
const { decode } = require('../utils/user-jwt');


// 登录
async function login(req, res, next) {
    const err = validationResult(req);
    // 如果验证错误，empty不为空
    if (!err.isEmpty()) {
        // 获取错误信息
        const [{ msg }] = err.errors;
        console.log(err)
            // 抛出错误，交给我们自定义的统一异常处理程序进行错误返回 
        next(boom.badRequest(msg));
    } else {
        let { username, password } = req.body;
        // md5加密
        password = md5(password);
        let user = await userService.validateUser(username, password)
        if (!user || user.length === 0) {
            res.json({
                code: CODE_ERROR,
                msg: '用户名或密码错误',
                data: null
            })
        } else {
            user = await userService.findUserByUsername(username)
                // 登录成功，签发一个token并返回给前端
            const token = jwt.sign(
                // payload：签发的 token 里面要包含的一些数据。
                { username },
                // 私钥
                PRIVATE_KEY,
                // 设置过期时间
                { expiresIn: JWT_EXPIRED }
            )
            res.json({
                code: CODE_SUCCESS,
                msg: '登录成功',
                data: {
                    token,
                    userData: user
                }
            })
        }
    }
}


// 注册
async function register(req, res, next) {
    const err = validationResult(req);
    if (!err.isEmpty()) {
        const [{ msg }] = err.errors;
        next(boom.badRequest(msg));
    } else {
        let { username, password } = req.body;
        let result = await userService.findUserByUsername(username);
        if (result) {
            return res.json({
                code: CODE_ERROR,
                msg: '用户已存在',
                data: null
            })
        }
        password = md5(password);
        result = await userService.insertUserInfo({ username, password })
        if (!result) {
            return res.json({
                code: CODE_ERROR,
                msg: '注册失败',
                data: null
            })
        }
        result = await userService.findUserByUsername(username)
        const token = jwt.sign({ username },
            PRIVATE_KEY, { expiresIn: JWT_EXPIRED }
        )
        res.json({
            code: CODE_SUCCESS,
            msg: '注册成功',
            data: {
                token,
                userData: result
            }
        })

    }
}

// 重置密码
async function resetPwd(req, res, next) {
    const err = validationResult(req);
    if (!err.isEmpty()) {
        const [{ msg }] = err.errors;
        next(boom.badRequest(msg));
    } else {
        let { username, oldPassword, newPassword } = req.body;
        oldPassword = md5(oldPassword);
        let data = await userService.validateUser(username, oldPassword)
        if (data) {
            if (newPassword) {
                newPassword = md5(newPassword);
                let user = userService.updateUserPassword(username, newPassword)
                    // console.log('密码重置===', user);
                if (!user || user.length === 0) {
                    res.json({
                        code: CODE_ERROR,
                        msg: '重置密码失败',
                        data: null
                    })
                } else {
                    res.json({
                        code: CODE_SUCCESS,
                        msg: '重置密码成功',
                        data: null
                    })
                }

            } else {
                res.json({
                    code: CODE_ERROR,
                    msg: '新密码不能为空',
                    data: null
                })
            }
        } else {
            res.json({
                code: CODE_ERROR,
                msg: '用户名或旧密码错误',
                data: null
            })
        }
    }
}

module.exports = {
    login,
    register,
    resetPwd
}